<?php
namespace Common\Model;
use Common\Model\BaseModel;
/**
 * 分类Model
 */
class CategoryModel extends BaseModel
{
	//自动验证
	protected $_validate = array(
		array('cname','require','分类名不能为空'),
		array('sort','number','排序必须为数字')
	);

	//传递id获得对应字段的数据，不传值默认获得全部数据
	public function getAllData($filed='all',$tree=true){
		if ($filed=='all') {
			$data=$this->order('sort')->select();
			if ($tree) {
				return \Common\Lib\Data::tree($data,'cname');
			}else{
				return $data;
			}
		}else{
			return $this->getField("cid,$field");
		}
	}

	//获得cid和field对应的数据
	public function getDataByCid($cid,$field='all'){
		if ($field=='all') {
			return $this->where("cid=$cid")->find();
		}else{
			return $this->where("cid=$cid")->getField($field);
		}
	}

	//获得cid的所有子栏目
	public function getChildData($cid){
		$data=$this->getAllData('all',false);
		$child=\Common\Lib\Data::channelList($data,$cid);
		foreach ($child as $k => $v) {
			$childs[]=$v['cid'];
		}
		return $childs;
	}

	//添加分类
	public function store(){
		if (!$this->create()) return false;
		return $this->add();
	}

	//删除分类
	public function deleteData($cid=null){
		$cid=is_null($cid) ? I('get.cid') : $cid;
        $child=$this->getChildData($cid);
        if(!empty($child)){
            $this->error='请先删除子分类';
            return false;
        }
        $articleData=D('Article')->getDataByCid($cid);
        if(!empty($articleData)){
            $this->error='请先删除此分类下的文章';
            return false;
        }
        if($this->where(array('cid'=>$cid))->delete()){
            return true;
        }else{
            return false;
        }
	}


}